/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var getKthFromEnd = function(head, k) {
  let length = 0, temp = head;
  while(temp) {
    length++;
    temp = temp.next;
  }
  if(k < 0 || k > length) return null;
  let result = null;
  temp = head;k--;
  while(temp) {
    temp = temp.next;
    if(k) k--;
    else {
      if(result) result = result.next;
      else result = head;
    }
  }
  return result.val;
};
